/**
 * 二维码Code
 */

import Taro from "@tarojs/taro";
import { onMounted, ref, shallowRef, useId, watch } from "vue";
import drawQrcode from "weapp-qrcode-canvas-2d";

type QRcodeOptions = {
  /**
   * 文本内容
   */
  text?: string;

  /**
   * 二维码宽度，与canvas的width保持一致
   */
  width: number;

  /**
   * 空白内边距
   */
  padding?: number;

  /**
   * 内边距颜色,默认与background一致
   */
  paddingColor?: string;

  /**
   * 背景色
   */
  background?: string;
  /**
   * 码的颜色
   */
  foreground?: string;
  /**
   * 二维码的计算模式，默认值-1
   */
  typeNumber?: number;
  /**
   * 二维码纠错级别，默认值为高级，取值：{ L: 1, M: 0, Q: 3, H: 2 }
   */
  correctLevel?: 1 | 2 | 3;

  /**
   * 在 canvas 上绘制图片，层级高于二维码，v1.1.1+版本支持。具体使用见：例子2
   */
  image?: {
    imageResource: string;
    width: number;
    height: number;
    round?: boolean;
  };

  /**
   * autoToImagePath,默认 true
   */
  autoToImagePath?: boolean;
};

export default function useQRcode(
  options: QRcodeOptions = { autoToImagePath: true, width: 300 }
) {
  const canvasId = "qrcode_" + useId();

  const canvas = shallowRef();
  const text = ref(options?.text || undefined);
  const imagePath = ref();

  const toCreate = () => {
    const { autoToImagePath = true, ...rest } = options;

    drawQrcode({
      ...rest,
      canvas: canvas.value,
      text: text.value,
    }).then(() => {
      if (autoToImagePath) canvasToTempFilePath();
    });
  };

  const canvasToTempFilePath = () => {
    const { width } = options;

    // 获取临时路径
    Taro.canvasToTempFilePath({
      canvas: canvas.value,
      x: 0,
      y: 0,
      width,
      height: width,
      destWidth: width * 2,
      destHeight: width * 2,
      success(res) {
        imagePath.value = res.tempFilePath;
      },
      fail(res) {
        console.error(res);
      },
    });
  };

  onMounted(() => {
    Taro.createSelectorQuery()
      .select("#" + canvasId)
      .fields({ node: true, size: true })
      .exec((res) => {
        canvas.value = res[0].node;
        if (text.value) toCreate();
      });
  });

  watch(text, (val) => {
    if (val) {
      toCreate();
    }
  });

  return {
    text,
    imagePath,
    canvasId,
  };
}
